package cn.lzj.service.base.impl;

import cn.lzj.Utils.randomUtil;
import cn.lzj.mapper.RegisterMapper;
import cn.lzj.pojo.User;
import cn.lzj.service.base.RegisterService;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
public class registerServiceImpl implements RegisterService {

    @Resource
    private RegisterMapper registerMapper;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public void registerUser(User user) {
        registerMapper.RegisterUser(user);
    }

    /**
     *
     * @param phone 电话号码
     * @return
     */
    @Override
    public String getCodeNum(String phone) {
        //redisTemplate的存储形式： key：phone  value：code
        BoundValueOperations<String, String> ops = redisTemplate.boundValueOps(phone);
        String code = ops.get();

        if(code == null){
            synchronized (this){
                code = ops.get();
                if(code == null){
                    code = randomUtil.createCode();

                    System.out.println("创建了新的code");
                    //将查询结果写入到缓存
                    ops.set(code,1, TimeUnit.MINUTES);
                }
            }
        }
        return code;
    }
}
